<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <form action="/" class="search-input">
      <van-search
        v-model="searchValue"
        placeholder="请输入搜索关键词"
        clearable
        show-action
        background="#3296fa"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>
    <div class="search-content">
      <!-- 搜索结果 -->
      <search-result
        v-if="isResultShow"
        :search-value="searchValue"
      ></search-result>
      <!-- 搜索建议 -->
      <search-suggestion
        v-else-if="searchValue"
        :search-value="searchValue"
        @search-suggestion="onSearch"
      ></search-suggestion>
      <!-- 历史记录 -->
      <search-history
        v-else
        :history-list="historyList"
        @delete="deleteHistoryList"
        @search-suggestion="onSearch"
      ></search-history>
    </div>
  </div>
</template>

<script>
import SearchSuggestion from './components/search-suggestion'
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import { getItem, setItem, KEY_MAP } from '@/utils/storage'
export default {
  name: 'Search',
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult
  },
  data() {
    return {
      searchValue: '',
      isResultShow: false,
      historyList: getItem(KEY_MAP.MY_HISTORY) || []
    }
  },
  watch: {
    historyList() {
      // 本地化存储
      setItem(KEY_MAP.MY_HISTORY, this.historyList)
    }
  },
  methods: {
    onSearch(suggestionValue) {
      if (suggestionValue) {
        this.searchValue = suggestionValue
      }

      // 每搜索一次保存一次历史记录
      this.saveHistoryList(this.searchValue)

      this.isResultShow = true
    },
    saveHistoryList(val) {
      const index = this.historyList.indexOf(val)
      if (index !== -1) {
        this.historyList.splice(index, 1)
      }
      this.historyList.unshift(val)
    },
    deleteHistoryList(index) {
      // 如果是 -1 表示删除全部
      if (index === -1) {
        this.historyList = []
      } else {
        this.historyList.splice(index, 1)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  .search-input {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 50;
  }
  .search-content {
    padding-top: 54px;
  }
}
</style>
